import React, { Component, Fragment } from "react";
import { Form, Input, Button, Row, Col } from "antd";
import "./index.scss";
import { UserOutlined, LockOutlined, UnlockOutlined } from "@ant-design/icons";
import { withRouter } from "react-router-dom";

//引入密码正则表达式变量
import {
  verification_password,
  validate_email,
} from "../../utils/verification";
//引入加密插件
import CryptoJS from "crypto-js";
//API
import { Login } from "../../api/account";
import Code from "../../components/code/index";
//方法
import { setToken, setUsername } from "../../utils/cookiens";

class Loginfrom extends Component {
  //初始化状态
  state = {
    username: "",
    password: "",
    code: "",
    moudle: "login",
    loading: false,
  };
  //react没有双向数据绑定的概念
  // .then方法里面的第二个回调不存在的时候,会调用catch方法
  //如果存在第二个回调,则不会执行catch
  onFinish = (value) => {
    const resquestData = {
      code: this.state.code,
      username: this.state.username,
      password: CryptoJS.MD5(this.state.password).toString(),
    };
    this.setState({ loading: true });
    Login(resquestData)
      .then((res) => {
        this.setState({ loading: false });
        //存储token
        const data = res.data.data;
        setToken(data.token);
        setUsername(data.username);
        //路由跳转
        this.props.history.push("/index");
      })
      .catch((error) => {
        this.setState({ loading: false });
      });
    console.log("Received values of form: ", value);
  };
  //切换注册页面  登录
  toggleFrom = () => {
    //请父组件的方法
    this.props.switchFrom("register");
  };

  //邮箱框输入事件
  inputChangUsername = (event) => {
    let value = event.target.value;
    this.setState({
      username: value,
    });
  };
  //密码框输入事件
  inputChangPassword = (event) => {
    let value = event.target.value;
    this.setState({
      password: value,
    });
  };
  //验证码框输入事件
  inputChangCode = (event) => {
    let value = event.target.value;
    this.setState({
      code: value,
    });
  };
  render() {
    const { username, moudle, loading } = this.state;
    const _this = this;
    return (
      <Fragment>
        <div className="form-header">
          <h4 className="login">登录</h4>
          <span onClick={this.toggleFrom}>账号注册</span>
        </div>
        <Form
          name="normal_login"
          className="login-form"
          initialValues={{
            remember: true,
          }}
          onFinish={this.onFinish}
        >
          <Form.Item
            name="username"
            rules={[
              {
                required: true,
                message: "请输入邮箱",
              },
              //{ type: "email", message: "邮箱格式不正确" },
              ({ getFieldValue }) => ({
                //ES6结构
                validator(_, value) {
                  if (validate_email(value)) {
                    _this.setState({
                      code_button_disable: false,
                    });
                    return Promise.resolve("邮箱格式不正确");
                  }
                },
              }),
            ]}
          >
            <Input
              value={username}
              onChange={this.inputChangUsername}
              prefix={<UserOutlined className="site-form-item-icon" />}
              placeholder="Email"
            />
          </Form.Item>
          <Form.Item
            name="password"
            rules={[
              {
                required: true,
                message: "密码不能为空",
              },
              {
                pattern: verification_password,
                message: "请输入大于6位小于20位字母和数字",
              },
            ]}
          >
            <Input
              onChange={this.inputChangPassword}
              prefix={<LockOutlined className="site-form-item-icon" />}
              type="password"
              placeholder="Password"
            />
          </Form.Item>
          <Form.Item
            name="code"
            rules={[
              {
                required: true,
                message: "验证码不能为空",
              },
              { len: 6, message: "请输入6位的验证码" },
            ]}
          >
            <Row gutter={13}>
              <Col span={15}>
                <Input
                  onChange={this.inputChangCode}
                  prefix={<UnlockOutlined className="site-form-item-icon" />}
                  type="password"
                  placeholder="Code"
                />
              </Col>
              <Col span={9}>
                <Code username={username} moudle={moudle}></Code>
              </Col>
            </Row>
          </Form.Item>
          <Form.Item>
            <Button
              loading={loading}
              type="primary"
              block
              className="login-form-button"
              htmlType="submit"
            >
              登录
            </Button>
          </Form.Item>
        </Form>
      </Fragment>
    );
  }
}
export default withRouter(Loginfrom);
